package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.List;

@Service
public class StatementItemServiceImpl implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private StatementServiceImpl statementService;

    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectForList(qo));
    }

    @Override
    @Transactional // 原子性
    public void saveItems(@RequestBody List<StatementItem> statementItems) {
        // 删除末尾携带的数据并返回一个对象
        StatementItem temp = statementItems.remove(statementItems.size() - 1);
        // 获取携带对象的优惠价格
        BigDecimal discountAmount = temp.getItemPrice();
        // 通过id获取数据库里statement对象
        Statement statement = statementService.get(temp.getStatementId());
        // 如果客人已支付
        if (Statement.STATUS_PAID.equals(statement.getStatus())) {
            throw new BusinessException("不可对已支付订单进行保存操作");
        }
        // 删除之前明细
        statementItemMapper.deleteItemsByStatementId(statement.getId());
        // 总的价格
        BigDecimal totalAmount = new BigDecimal(0);
        // 总的数量
        BigDecimal totalQuantity = new BigDecimal(0);
        // 如果删除后数组大小还大于0,说明有明细
        if (statementItems.size() > 0) {
            for (StatementItem item : statementItems) {
                statementItemMapper.insert(item);
                // 统计总金额
                totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
                // 统计总数量
                totalQuantity = totalQuantity.add(item.getItemQuantity());
            }
        }
        // 如果优惠金额比总金额还高,属于非法操作
        if (totalAmount.compareTo(discountAmount) < 0) {
            throw new BusinessException("非法操作,优惠金额大于总金额");
        }
        statementService.updateAmount(statement.getId(),totalAmount,totalQuantity,discountAmount);
    }

    @Override
    public void deleteByStatementId(Long dictId) {
        statementItemMapper.deleteItemsByStatementId(dictId);
    }
}
